﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VFTray.Mi
{
	internal partial class DlgVarification : Form
	{
		internal DlgVarification(ProcessVerify pv)
		{
			_pv = pv;
			InitializeComponent();
			Text = "关于 " + GlobalParams.MF.OrgTitle;
			labelTitle.Text = Text + Environment.NewLine
				+ System.Diagnostics.FileVersionInfo.GetVersionInfo(Application.ExecutablePath).FileVersion;
			textBoxGuid.Text = pv.Guid;
		}

		private ProcessVerify _pv;
		private void buttonOK_Click(object sender, EventArgs e)
		{
			DialogResult = DialogResult.OK;
			Close();
		}

		internal EventHandler<Tuple<string, string>> EVerify;
		private void buttonVerify_Click(object sender, EventArgs e)
		{
			if (MessageBox.Show(this, "确定要对当前软件进行验证吗？" + Environment.NewLine + "请检查验证码是否有误", "请确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return;

			if(string.IsNullOrEmpty(textBoxVerifyID.Text))
			{
				MessageBox.Show(this, "验证码为空", "ERROR");
				return;
			}

			int rtn = 0;
			try
			{
				string guid = _pv.LoadGuid(true);

				string str_bydate_crypt32 = textBoxVerifyID.Text;
				var by_date_crypt = CodeHelper.FromBase32String(str_bydate_crypt32);
				var by_date = DESHelper.Decrypt(by_date_crypt, guid);

				string str_date = Encoding.ASCII.GetString(by_date);
				string cd = str_date.Substring(0, 8);
				string dd = str_date.Substring(8, 8);

				rtn = _pv.UpdateData(Environment.CurrentDirectory, dd);
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine("Varification " + ex.Message);
				rtn= - 1;
			}
			if (rtn == 0)
			{
				labelVTime.Text = _pv.GetExpiredS();
				MessageBox.Show(this, "验证通过", "OK");
			}
			else
			{
				MessageBox.Show(this, "验证错误 " + rtn.ToString(), "ERROR");
			}
		}

		internal int Varification(string code)
		{
			try
			{
				string guid = _pv.LoadGuid(true);

				string str_bydate_crypt32 = code;
				var by_date_crypt = Mi.CodeHelper.FromBase32String(str_bydate_crypt32);
				var by_date = Mi.DESHelper.Decrypt(by_date_crypt, guid);

				string str_date = Encoding.ASCII.GetString(by_date);
				string cd = str_date.Substring(0, 8);
				string dd = str_date.Substring(8, 8);

				int rnt = _pv.UpdateData(Environment.CurrentDirectory, dd);
				return rnt;
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine("Varification " + ex.Message);
				return -1;
			}

		}

		private void DlgVarification_Load(object sender, EventArgs e)
		{
			textBoxGuid.Text = _pv.Guid;
			labelVTime.Text = _pv.GetExpiredS();

		}

		private void DlgVarification_FormClosing(object sender, FormClosingEventArgs e)
		{
			_pv.updateVerify(true);
		}
	}
}
